import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meiduo_mall.settings.dev')
import sys
sys.path.insert(0, '../../../')
import django
django.setup()
from collections import OrderedDict
from django.conf import settings
from django.template import loader
from contents.models import ContentCategory, Content
from goods.models import GoodsChannel, GoodsCategory


def generate_static_index_html():

    # =====================生成字典格式数据=======================
    # 1.创建有序字典,用来存放频道列表字典
    categories = OrderedDict()
    # 2.筛选商品分类,按照分类id和序号排序
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 3.遍历频道
    for channel in channels:
        # 分组id
        group_id = channel.group_id

        # 将频道id添加到频道列表字典中
        if group_id not in categories:
            # 构建频道组
            categories[group_id] = {
                'channels': [],
                'sub_cats': []
            }

        # 4.获取当前频道的分类名称
        cat1 = channel.category
        # 一级分类数据
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })

        # 5.获取二级分类
        cat2s = GoodsCategory.objects.filter(parent=cat1)

        for cat2 in cat2s:
            cat2.sub_cats = []

            # 6.获取三级分类
            cat3s = GoodsCategory.objects.filter(parent=cat2)
            for cat3 in cat3s:
                # cat2下三级分类数据
                cat2.sub_cats.append(cat3)

            # 7.追加到频道列表
            categories[group_id]['sub_cats'].append(cat2)

    # =====================生成首页广告部分数据=======================
    # 1.广告内容字典
    contents_dict = {}

    # 2.获取所有首页广告数据
    content_categories = ContentCategory.objects.all()

    # 3.获取广告分类
    for cat in content_categories:
        # 4.根据广告分类 提取广告,并筛选
        contents_dict[cat.key] = Content.objects.filter(category=cat, status=True).order_by('sequence')

    # 第二部分: 模板渲染部分:
    # 把上面两部分获取的有序字典和字典作为变量,拼接新的字典 context
    context = {
        'categories': categories,
        'contents': contents_dict
    }

    # =====================获取模板,把数据添加进去生成页面====================

    # 6.获取 'index.html' 模板
    template = loader.get_template('index.html')

    # 7.渲染数据
    html_text = template.render(context)

    # 8.拼接 渲染后的html 生成到的前端服务器地址
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')

    # 以写的权限,将渲染过的模板重新生成, 写入到文件中.
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)


if __name__ == '__main__':
    generate_static_index_html()
    # import datetime
    # # 取当前时间
    # from django.utils import timezone
    #
    # print(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
    # print(timezone.localtime().strftime('%Y%m%d%H%M%S'))
